package com.zp.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;

import javax.servlet.ServletContext;

import com.sun.jersey.core.header.FormDataContentDisposition;

/**
 * File util
 * 
 * @author chenlijun08@gmail.com
 * 
 * @date 2014/1/20
 * 
 * @version 1.0
 * 
 */
public class FileUtil {

	private static final FileUtil fileUtil = new FileUtil();

	public static FileUtil getInstance() {
		return fileUtil;
	}

	public void deleteFile(String path) {
		File f = new File(path);
		if (!f.exists()) {
			return;
		}
		f.delete();
	}

	public String getSavePath(String path) {
		File directory = new File(path);
		if (!directory.exists() && !directory.isDirectory()) {
			directory.mkdirs();
		}
		return path;
	}

	/**
	 * Get file name that combined with year month date time, for example:
	 * 2012112143825.jpg
	 * 
	 * @param postfix
	 *            the postfix of file
	 * 
	 * @return String name of file saved
	 */
	public String getFileName(String postfix) {
		Calendar calCurrent = Calendar.getInstance();
		StringBuilder builder = new StringBuilder();
		int intDay = calCurrent.get(Calendar.DATE);
		int intMonth = calCurrent.get(Calendar.MONTH) + 1;
		int intYear = calCurrent.get(Calendar.YEAR);
		int intHour = calCurrent.get(Calendar.HOUR_OF_DAY);
		int intMinute = calCurrent.get(Calendar.MINUTE);
		int intSecond = calCurrent.get(Calendar.SECOND);
		builder.append(String.valueOf(intYear))
				.append(String.valueOf(intMonth))
				.append(String.valueOf(intDay)).append(String.valueOf(intHour))
				.append(String.valueOf(intMinute))
				.append(String.valueOf(intSecond)).append(postfix);
		return builder.toString();
	}

	/**
	 * create image folder
	 * 
	 * @return folder name
	 */
	public String createDirctory() {
		Calendar calCurrent = Calendar.getInstance();
		StringBuilder builder = new StringBuilder();
		int intweek = calCurrent.get(Calendar.WEEK_OF_MONTH);
		int intMonth = calCurrent.get(Calendar.MONTH) + 1;
		int intYear = calCurrent.get(Calendar.YEAR);
		builder.append(String.valueOf(intYear))
				.append(String.valueOf(intMonth))
				.append(String.valueOf(intweek));
		return builder.toString();
	}

	/**
	 * save file
	 * 
	 * @param input
	 *            the input stream of file
	 * @param fileDisposition
	 *            filename information
	 * @return String save path file
	 */
	public String saveFile(InputStream input,
			FormDataContentDisposition fileDisposition,ServletContext context) {
		String savePath = null;
		long total = Constant.ZERO;
		boolean tooBig = false;
		File file = null;
		BufferedOutputStream bufferOutputStream = null;
		String fileFullName = fileDisposition.getFileName();
		if (!("".equals(fileFullName)) && fileFullName != null) {
			String postfix = fileFullName.substring(fileFullName.indexOf("."),
					fileFullName.length());
			if (Constant.JPEG_POSTFIX.equals(postfix)
					|| Constant.JPE_POSTFIX.equals(postfix)
					|| Constant.JPG_POSTFIX.equals(postfix)
					|| Constant.BMP_POSTFIX.equals(postfix)
					|| Constant.GIF_POSTFIX.equals(postfix)
					|| Constant.PNG_POSTFIX.equals(postfix)) {
				savePath = Constant.IMAGE_SAVE_PATH;
			} else {

				savePath = Constant.COMMON_SAVE_PATH;

			}
			//savePath=context.getRealPath(Constant.SERVER_CONTENT_PATH)+savePath;
			//String directory = savePath + this.createDirctory();
			String directory = Constant.PARENT_PATH+savePath + this.createDirctory();
			File f = new File(directory);
			if (!f.exists()) {
				f.mkdir();
			}
			try {
				file = new File(directory.concat("\\"),
						this.getFileName(postfix));
				bufferOutputStream = new BufferedOutputStream(
						new FileOutputStream(file));
				int length = Constant.ZERO;
				byte[] buff = new byte[Constant.IMAGE_BUFFER];
				while (Constant.NEGATIVE_ONE != (length = input.read(buff))) {
					total += length;
					if (total > Constant.MAX_IMAGE_SIZE) {
						tooBig = true;
						break;
					} else {
						bufferOutputStream.write(buff, Constant.ZERO, length);
					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					bufferOutputStream.flush();
					bufferOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
			if (!tooBig) {
				savePath = file.getPath().replace("\\", "/");
				savePath = savePath.substring(savePath
						.indexOf(Constant.UPLOAD_FOLDER));
			} else {
				if (file != null & file.exists()) {
					file.delete();
				}
				savePath = Constant.MAX_IMAGE_SIZE_MESSAGE;

			}

		}
		return savePath;
	}
}
